package top.moonkit.rs_pro.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import top.moonkit.rs_pro.entity.User;
import top.moonkit.rs_pro.entity.vo.RegisterRequestVO;
import top.moonkit.rs_pro.exception.BusinessException;
import top.moonkit.rs_pro.mapper.UserMapper;
import top.moonkit.rs_pro.service.LoginCheckCodeService;
import top.moonkit.rs_pro.service.UserService;
import org.springframework.stereotype.Service;
import top.moonkit.rs_pro.utils.Mu;

import java.util.Date;

import static top.moonkit.rs_pro.entity.table.UserTableDef.USER;

/**
 * 用户表 服务层实现。
 *
 * @author moon
 * @since 0.0.1
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>  implements UserService{

    @Autowired
    private LoginCheckCodeService loginCheckCodeService;

    @Override
    public boolean checkEmailExists(String email) {
        return findByEmail(email) != null;
    }

    @Override
    public User registerUser(RegisterRequestVO vo) {

        // 检查邮箱是否已存在
        if (checkEmailExists(vo.getAccount())) {
            throw new BusinessException(Mu.m("email.exists"));
        }

        // 检查两次密码是否一致
        if (vo.getPassword() != null && !vo.getPassword().equals(vo.getConfirmPassword())) {
            throw new BusinessException(Mu.m("person.password_not_match"));
        }else {
            if (!loginCheckCodeService.validateCode(vo.getAccount(), vo.getCode())){
                throw new BusinessException(Mu.m("login.code_error"));
            }
        }

        // 创建用户对象
        User user = new User();
        user.setEMail(vo.getAccount());
        user.setPhoneNumber(vo.getPhone());
        // 密码加密存储
        user.setPassword(BCrypt.hashpw(vo.getPassword()));
        user.setCreateTime(new Date());

        // 保存用户
        this.save(user);
        return user;
    }

    @Override
    public User findByEmail(String email) {
        return this.getOne(
                QueryWrapper.create()
                        .eq(User::getEMail, email)
        );
    }

    @Override
    public User findUserByAccount(String account) {
        // 先按手机号查找
        User user = this.getOne(
                QueryWrapper.create()
                                .and(USER.PHONE_NUMBER.eq(account))
        );

        // 如果没找到，再按邮箱查找
        if (user == null) {
            user = this.getOne(QueryWrapper.create().and(USER.E_MAIL.eq(account)));
        }

        return user;
    }
}
